<template>
  <div>
    <div
        v-show="dialogVisible"
        :style="{ left: position.x + 'px', top: position.y + 'px' }"
        @mousedown="startDrag"
        class="draggable meeting-video-list">
      <div class="meeting-video-header">
        <div @click="hide" style="display: flex;align-items: center;padding: 12px 0">
          <div>最小化</div>
        </div>
      </div>
      <div class="video-grid-box">
        <div class="video-container video-container2" id="local-player">
          <div class="user-info">
            <el-avatar size="small" :src="defaultAvatar"></el-avatar>
            <span style="margin-left: 12px">我</span>
          </div>
        </div>
        <div class="video-grid" >
          <el-row :gutter="10" v-if="isInMeeting">
            <el-col
                v-for="user in remoteUsers"
                :key="user.uid"
                :span="24"
            >
              <div class="video-container" :id="`user-${user.uid}`">
                <div class="user-info">
                  <el-avatar size="small" :src="defaultAvatar"></el-avatar>
                  <span style="margin-left: 6px;color: #ffffff;font-weight: bold">{{ getTrueName(user.uid) }}</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="control-bar">
        <el-row type="flex" justify="space-between" align="middle">
          <el-col :span="24">
            <div class="control-buttons">
              <el-tooltip content="麦克风" placement="top">
                <el-button
                    :type="isAudioEnabled ? 'primary' : 'info'"
                    circle
                    size="mini"
                    @click="toggleAudio"
                    :icon="isAudioEnabled ? 'el-icon-microphone' : 'el-icon-turn-off-microphone'"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="摄像头" placement="top">
                <el-button
                    :type="isVideoEnabled ? 'primary' : 'info'"
                    circle
                    size="mini"
                    @click="toggleVideo"
                    :icon="isVideoEnabled ? 'el-icon-video-camera' : 'el-icon-video-camera-solid'"
                ></el-button>
              </el-tooltip>
              <!--            <el-tooltip content="退出会议" placement="top">-->
              <!--              <el-button-->
              <!--                  type="danger"-->
              <!--                  circle-->
              <!--                  size="mini"-->
              <!--                  @click="leaveChannel"-->
              <!--                  icon="el-icon-phone"-->
              <!--              ></el-button>-->
              <!--            </el-tooltip>-->
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="meeting-box" v-if="!dialogVisible" @click="dialogVisible = true">
      <i class="el-icon-video-camera-solid" style="font-size: 24px;color: #fffdef"></i>
    </div>
  </div>
</template>

<script>
import AgoraRTC from 'agora-rtc-sdk-ng'
import CallDialog from './CallDialog.vue'
export default {
  name: 'VideoConference',
  components: {
    CallDialog,
  },
  props: {
    agoraConfig: {
      type: Object,
      required: true,
      default: () => ({})
    },
    inviteList: {
      type: Array,
      required: true,
      default: () => []
    },
    applyForm: {
      type: Object,
      required: true,
      default: () => ({})
    }
  },
  computed: {
    trueName() {
      return this.$authInfo.getUser().trueName
    }
  },
  data() {
    return {
      position: { x: 50, y: 100 },
      isDragging: false,
      offset: { x: 0, y: 0 },
      defaultAvatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      dialogVisible: true,
      client: null,
      localAudioTrack: null,
      localVideoTrack: null,
      remoteUsers: [],
      isAudioEnabled: true,
      isVideoEnabled: true,
      isInMeeting: false,
      ringTone: null
    }
  },
  async mounted() {
    this.playRingTone()
    await this.handleAcceptCall()
  },
  beforeDestroy() {
    this.stopRingTone()
    this.leaveChannel()
  },
  methods: {
    hide() {
      this.dialogVisible = false
    },
    startDrag(event) {
      this.isDragging = true;
      this.offset.x = event.clientX - this.position.x;
      this.offset.y = event.clientY - this.position.y;
      window.addEventListener('mousemove', this.onDrag);
      window.addEventListener('mouseup', this.stopDrag);
    },
    onDrag(event) {
      if (this.isDragging) {
        const newX = event.clientX - this.offset.x;
        const newY = event.clientY - this.offset.y;

        // 限制拖拽范围在屏幕内
        this.position.x = Math.max(0, Math.min(newX, window.innerWidth - 100)); // 假设div宽度为100px
        this.position.y = Math.max(0, Math.min(newY, window.innerHeight - 100)); // 假设div高度为100px
      }
    },
    stopDrag() {
      this.isDragging = false;
      window.removeEventListener('mousemove', this.onDrag);
      window.removeEventListener('mouseup', this.stopDrag);
    },
    getTrueName(uid) {
      if (uid === this.applyForm.userId) {
        console.log(this.applyForm,'applyForm');
        return '患者-' + this.applyForm.inquiryPatientName
      }
      let find = this.inviteList.find(item => item.expertDoctorId === uid)
      console.log('find',find);
      return find ? find.type  + '-' + find.expertDoctorName : uid
    },
    playRingTone() {
      this.ringTone = new Audio()
      // this.ringTone.src = require('@/assets/audio/ringtone.mp3')
      this.ringTone.loop = true
      this.ringTone.play().catch(error => {
        console.log('自动播放被阻止:', error)
      })
    },

    stopRingTone() {
      if (this.ringTone) {
        this.ringTone.pause()
        this.ringTone.currentTime = 0
      }
    },

    async handleAcceptCall() {
      this.stopRingTone()
      this.isInMeeting = true
      try {
        await this.initializeAgora()
        await this.joinChannel()
      } catch (error) {
        console.log(error, 'erro');
        this.$message.error('初始化失败：' + error.message)
        this.isInMeeting = false
      }
    },

    handleRejectCall() {
      this.stopRingTone()
      this.$message({
        type: 'info',
        message: '您已拒绝加入会议'
      })
      this.$router.push('/')
    },

    async initializeAgora() {
      console.log('init');
      this.client = AgoraRTC.createClient({ mode: 'rtc', codec: 'h264' })

      this.client.on('user-published', async (user, mediaType) => {
        await this.client.subscribe(user, mediaType)
        if (mediaType === 'video') {
          if (!this.remoteUsers.find(u => u.uid === user.uid)) {
            this.remoteUsers.push(user)
          }
          setTimeout(() => {
            user.videoTrack.play(`user-${user.uid}`)
          }, 100)
        }
        if (mediaType === 'audio') {
          user.audioTrack.play()
        }
      })

      this.client.on('user-left', async (user) => {
        this.remoteUsers = this.remoteUsers.filter(u => u.uid !== user.uid)
      })
    },

    async joinChannel() {
      try {
        const uid = await this.client.join(this.agoraConfig.appId, this.agoraConfig.channel, this.agoraConfig.token || null, this.agoraConfig.uid || null)
        this.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack()
        this.localVideoTrack = await AgoraRTC.createCameraVideoTrack()
        await this.client.publish([this.localAudioTrack, this.localVideoTrack])
        this.localVideoTrack.play('local-player')
        console.log('this.localVideoTrack.play',this.localVideoTrack.play);
        this.$message.success('成功加入会议')
      } catch (error) {
        this.$message.error('加入会议失败: ' + error.message)
        this.isInMeeting = false
      }
    },

    async leaveChannel() {
      if (this.localAudioTrack) {
        this.localAudioTrack.stop()
        this.localAudioTrack.close()
      }
      if (this.localVideoTrack) {
        this.localVideoTrack.stop()
        this.localVideoTrack.close()
      }
      await this.client.leave()
      this.remoteUsers = []
      this.isInMeeting = false
      this.dialogVisible = false
      this.$message.success('已退出会议')
    },

    async toggleAudio() {
      if (this.localAudioTrack) {
        this.isAudioEnabled = !this.isAudioEnabled
        this.localAudioTrack.setEnabled(this.isAudioEnabled)
      }
    },

    async toggleVideo() {
      if (this.localVideoTrack) {
        this.isVideoEnabled = !this.isVideoEnabled
        this.localVideoTrack.setEnabled(this.isVideoEnabled)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.meeting-box {
  cursor: pointer;
  position: fixed;
  height: 50px;
  width: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #006db8;
  border-radius: 50%;
  bottom: 50px;
  left: 50px;
  z-index: 999;
}
.meeting-video-header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 12px;
  background-color: #f0f6fb;
}
.draggable {
  width: 100px;
  height: 100px;
  position: fixed;
  cursor: move;
  z-index: 999;
}
.video-grid-box {
  flex-grow: 1;
  position: relative;
  .video-container2 {
    width: 100% !important;
    height: 100% !important;
    border: none !important;
  }
  .video-grid {
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
    width: 200px;
    overflow: auto;
    padding: 12px;
    z-index: 2;
  }
}
.meeting-video-list {
  background-color: #000;
  width: 700px;
  min-height: 520px;
  display: flex;
  flex-direction: column;
  max-height: 490px;
  overflow: hidden;
  .control-bar {
    flex-shrink: 0;
    padding:10px 20px;
    background: rgba(0, 0, 0, 0.8);
    z-index: 100;
  }
}


.control-buttons {
  text-align: center;
}

.control-buttons .el-button {
  margin: 0 10px;
}

.video-grid {
  padding-right: 20px;
}

.video-container {
  width: 100%;
  height: 120px;
  background: #2c2c2c;
  position: relative;
  overflow: hidden;
  margin-bottom: 8px;
  border: 1px solid #e2e2e2;
}

.user-info {
  position: absolute;
  bottom: 2px;
  left: 5px;
  color: white;
  z-index: 1;
  //background: rgba(0, 0, 0, 0.5);
  //padding: 5px 10px;
  //border-radius: 4px;
  display: flex;
  align-items: center;
}

.meeting-info {
  color: white;
}

.meeting-title {
  font-size: 16px;
}
</style>
